package com.chamberlain.framework.security.provider;

import com.chamberlain.common.exception.ServiceException;
import com.chamberlain.common.utils.SecurityUtils;
import com.chamberlain.framework.web.service.HarmonyUserDetailsServiceImpl;
import com.chamberlain.framework.web.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author: CYY
 * @date: 2024/3/28
 */
@Component
public class HarmonyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private HarmonyUserDetailsServiceImpl userDetailsService;




    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();// 这个获取表单输入中返回的用户名;
        Object password = authentication.getCredentials();//这个获取表单输入中返回的密码;

        // 这里构建来判断用户是否存在和密码是否正确
        UserDetails userInfo = userDetailsService.loadUserByUsername(userName); // 这里调用我们的自己写的获取用户的方法；

        if(!SecurityUtils.matchesPassword(password.toString(),userInfo.getPassword())){
            //log.info("用户不存在/密码错误,{}", userName);
            throw new ServiceException("用户不存在/密码错误");
        }

        Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();
        // 构建返回的用户登录成功的token
        return new UsernamePasswordAuthenticationToken(userInfo, userInfo.getPassword(), authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
//        return authentication.equals(UsernamePasswordAuthenticationToken.class);
        // 这里直接改成 return true;表示是支持这个执行
        return true;
    }
}
